package connect

import (
	"net"
	"sync"
)

var a uint32

func init() {
	a = 1
}

type PoolHandler struct {
}

func (p *PoolHandler) Add(n *NetNode)    {}
func (p *PoolHandler) Delete(n *NetNode) {}

//ConnPoolHand 。。连接池响应函数
type ConnPoolHand func(*NetNode, []byte)

//ConnPool ..连接池
type ConnPool struct {
	NetNodePool  sync.Map
	HandlerEvent CoonPool_I
	handler      map[uint32]ConnPoolHand
	quit         chan uint32
}

//NewConnPool ..新建一个连接容器
func NewConnPool(event CoonPool_I) (pool *ConnPool) {
	pool = &ConnPool{
		NetNodePool:  sync.Map{},
		HandlerEvent: event,
		handler:      make(map[uint32]ConnPoolHand),
		quit:         make(chan uint32, 100),
	}
	go func() {
		for {
			q := <-pool.quit
			pool.DeleteNetNode(q)
		}
	}()
	return
}

//AddNewConn ..添加一个网络节点
func (c *ConnPool) AddNewConn(conn net.Conn) {
	newconn := NewNetNode(a, conn, c.quit)
	c.NetNodePool.Store(a, newconn)
	c.HandlerEvent.Add(newconn)
	go newconn.Read(c.handler)
	a++
}

//DeleteNetNode 删除一个网络节点
func (c *ConnPool) DeleteNetNode(id uint32) {
	if n, ok := c.NetNodePool.Load(id); ok {
		c.HandlerEvent.Delete(n.(*NetNode))
		n.(*NetNode).Close()
		c.NetNodePool.Delete(id)
	}
}

//RegistHandler 注册目标响应函数
func (c *ConnPool) RegistHandler(purpose uint32, hand ConnPoolHand) {
	c.handler[purpose] = hand
}

//Range 循环函数
func (c *ConnPool) Range(f func(netnode *NetNode)) {
	c.NetNodePool.Range(func(_, value interface{}) bool {
		f(value.(*NetNode))
		return true
	})
}
